<?php

/**
 * This is the model class for table "ads".
 *
 * The followings are the available columns in table 'ads':
 * @property integer $ad_id
 * @property integer $user_id
 * @property string $title
 * @property string $content
 * @property integer $main_category
 * @property integer $type
 * @property string $image
 * @property integer $featured
 * @property string $contact_name
 * @property string $contact_email
 * @property string $contact_country
 * @property string $contact_state
 * @property string $contact_city
 * @property string $contact_phone
 * @property string $contact_cellphone
 * @property string $website
 * @property integer $expire_time
 * @property integer $status
 * @property integer $created
 * @property integer $updated
 * @property float $price
 * @property int $is_send_mail
 * @property int $is_send_mail_before
 */
class Ad extends CActiveRecord {

    const TYPE_EQUIPMENT = 1;
    const TYPE_RESUME = 2;
    const TYPE_JOB = 3;
    const TYPE_COMPANY_SOURCE = 4;
    const TYPE_SUPPLY = 5;
    const TYPE_VENDOR = 6;
    const TYPE_TECHNICAL = 7;
    const TYPE_ADVERTISE = 8;
    const IS_FEATURED = 1;
    const SENDED_MAIL = 1;
    const NOT_SEND_MAIL = 0;

    public $otherCategoryIds = array();

    const STATUS_PENDING = 0;
    const STATUS_APPROVE = 1;
    const STATUS_DENY = 2;
    const SCENARIO_UPDATE = 'update';

    public $expireDate = '';
    public $userName;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Ad the static model class
     */
    public static function model($className = __CLASS__) {
	return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	return '{{ads}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	// NOTE: you should only define rules for those attributes that
	// will receive user inputs.
	return array(
	    array('title, main_category, type', 'required'),
	    array('price', 'numerical'),
	    array('user_id, main_category, type, featured, expire_time, status, created, updated', 'numerical', 'integerOnly' => true),
	    array('title, image, website', 'length', 'max' => 255),
	    array('contact_name, contact_email', 'length', 'max' => 128),
	    array('contact_country', 'length', 'max' => 2),
	    array('contact_state, contact_city, contact_phone, contact_cellphone', 'length', 'max' => 60),
	    array('content, otherCategoryIds, expireDate, expire_featured, is_send_mail, is_send_mail_before, userName', 'safe'),
	    // The following rule is used by search().
	    // Please remove those attributes that should not be searched.
	    array('ad_id, user_id, title, content, main_category, type, image, featured, contact_name, contact_email, contact_country, contact_state, contact_city, contact_phone, contact_cellphone, expire_time, status, created, updated', 'safe', 'on' => 'search'),
	);
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	// NOTE: you may need to adjust the relation name and the related
	// class name for the relations automatically generated below.
	return array(
	    'user' => array(self::BELONGS_TO, 'User', 'user_id'),
	    'mainCategory' => array(self::BELONGS_TO, 'Category', 'main_category'),
	    'categories' => array(self::MANY_MANY, 'Category',
		'ads_categories(ad_id, category_id)'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'ad_id' => 'Ad',
	    'user_id' => 'User',
	    'title' => 'Title',
	    'content' => 'Content',
	    'main_category' => 'Main Category',
	    'type' => 'Type',
	    'image' => 'Image',
	    'featured' => 'Featured',
	    'contact_name' => 'Contact Name',
	    'contact_email' => 'Contact Email',
	    'contact_country' => 'Contact Country',
	    'contact_state' => 'Contact State',
	    'contact_city' => 'Contact City',
	    'contact_phone' => 'Contact Phone',
	    'contact_cellphone' => 'Contact Cellphone',
	    'expire_time' => 'Expire Time',
	    'status' => 'Status',
	    'created' => 'Created',
	    'updated' => 'Updated',
	);
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
	// Warning: Please modify the following code to remove attributes that
	// should not be searched.

	$criteria = new CDbCriteria;
	$criteria->with = 'user';
//	$criteria->compare('ad_id', $this->ad_id);
//	$criteria->compare('user_id', $this->user_id);
	$criteria->compare('title', $this->title, true);
	$criteria->compare('content', $this->content, true);
//	$criteria->compare('main_category', $this->main_category);
//	$criteria->compare('type', $this->type);
//	$criteria->compare('image', $this->image, true);
//	$criteria->compare('featured', $this->featured);
//	$criteria->compare('contact_name', $this->contact_name, true);
//	$criteria->compare('contact_email', $this->contact_email, true);
//	$criteria->compare('contact_country', $this->contact_country, true);
//	$criteria->compare('contact_state', $this->contact_state, true);
//	$criteria->compare('contact_city', $this->contact_city, true);
//	$criteria->compare('contact_phone', $this->contact_phone, true);
//	$criteria->compare('contact_cellphone', $this->contact_cellphone, true);
//	$criteria->compare('expire_time', $this->expire_time);
	$criteria->compare('status', $this->status);
//	$criteria->compare('created', $this->created);
//	$criteria->compare('updated', $this->updated);
//	$criteria->compare('updated', $this->updated);
	$criteria->compare('user.username', $this->userName, TRUE);

	$criteria->order = 'ad_id DESC';
	return new CActiveDataProvider($this, array(
	    'criteria' => $criteria,
	));
    }

    /**
     * before save action
     * @return boolean
     */
    public function beforeSave() {
	if (parent::beforeSave()) {
	    if ($this->isNewRecord) {
		$this->created = $this->updated = time();
		$this->user_id = user()->id;
	    } else {
		$this->updated = time();
	    }
	    return true;
	}

	return false;
    }

    public function afterSave() {
	parent::afterSave();

	//update other categorie
	if (!empty($this->otherCategoryIds)) {
	    //
	    $db = db();
	    $db->createCommand()->delete('{{ads_categories}}', 'ad_id = ' . $this->ad_id);
	    //insert new row
	    foreach ($this->otherCategoryIds as $catId) {
		$db->createCommand()->insert('{{ads_categories}}', array(
		    'ad_id' => $this->ad_id,
		    'category_id' => $catId
		));
	    }
	}

	if (!$this->isNewRecord) {
	    //clear meta data
	    app()->cache->delete('ad_meta_data_' . $this->ad_id);
	}
    }

    /**
     * add meta data
     * @param AdMeta $meta
     * @return boolean
     */
    public function addMeta($meta) {
	$meta->ad_id = $this->ad_id;
	return $meta->save();
    }

    public function instantiate($attributes) {
	switch ($attributes['type']) {
//	    case self::TYPE_COMPANY_SOURCE :
//		$className = 'CompanySource';
//		break;
	    case self::TYPE_VENDOR:
		$className = 'Vendor';
		break;
	    case self::TYPE_TECHNICAL:
		$className = 'Technical';
		break;
	    case self::TYPE_EQUIPMENT :
		$className = 'Equipment';
		break;
	    case self::TYPE_SUPPLY :
		$className = 'Supply';
		break;
	    case self::TYPE_JOB :
		$className = 'Job';
		break;
	    case self::TYPE_RESUME :
		$className = 'Resume';
		break;
	    case self::TYPE_ADVERTISE:
		$className = 'Advertise';
		break;
	    default :
		$className = 'Ad';
		break;
	}

	$model = new $className(null);

	return $model;
    }

    /**
     * get view from front end
     * @return type
     */
    public function getFrontendUrl() {
//	return url('/ad/view', array(
//	    'id' => $this->ad_id,
//	    'name' => $this->title
//	));
	return url('/ad/view', array(
	    'id' => $this->ad_id,
	    'name' => ''
	));
    }

    /**
     * get image
     */
    public function getImageUrl($size = '') {
	if ($this->type == Ad::TYPE_RESUME) {
	    return WWW_URL . 'images/img-resume.jpg';
	}
	if ($this->type == Ad::TYPE_JOB) {
	    return WWW_URL . 'images/img-job.jpg';
	}
	if ($this->image != '') {
	    switch ($size) {
		case 'thumb' :
		    $width = 200;
		    $height = 150;
		    break;
		case 'small' :
		    $width = 64;
		    $height = 64;
		    break;
		default :
		    $width = 800;
		    $height = 600;
		    break;
	    }
	    return ImageHelper::thumb($width, $height, UPLOAD_PATH . $this->image);
	}

	return UPLOAD_URL . 'icon_no-image.gif';
    }

    /**
     * get feature image( advertise)
     */
    public function getFeatureImgUrl($size = '') {
	if ($this->advertisement != '') {
	    switch ($size) {
		case 'thumb' :
		    $width = 200;
		    $height = 150;
		    break;
		case 'small' :
		    $width = 64;
		    $height = 64;
		    break;
		default :
		    return UPLOAD_URL . 'feature/' . $this->advertisement;
//		    $width = 800;
//		    $height = 600;
		    break;
	    }
	    return ImageHelper::thumb($width, $height, UPLOAD_PATH . 'feature/' . $this->advertisement);
	}
	if ($this->advertisement != '') {
	    
	}

	return UPLOAD_URL . 'icon_no-image.gif';
    }

    public function getTypeUrl() {
	switch ($this->type) {
	    case self::TYPE_EQUIPMENT :
		$type = 'equipment';
		break;
	    case self::TYPE_SUPPLY :
		$type = 'supply';
		break;
	    case self::TYPE_VENDOR:
		$type = 'vendor';
		break;
	    case self::TYPE_TECHNICAL:
		$type = 'technical';
		break;
	    case self::TYPE_JOB :
		$type = 'job';
		break;
	    case self::TYPE_RESUME :
		$type = 'resume';
		break;
	    default : $type = 'equipment';
		break;
	}

	return url('/ad/type', array(
	    'type' => $type
	));
    }

    /**
     * get text of type
     */
    public function getType() {
	switch ($this->type) {

	    case self::TYPE_EQUIPMENT :
		return 'Equipment';
	    case self::TYPE_SUPPLY :
		return 'Supply';
	    case self::TYPE_VENDOR:
		return 'Vendor';
	    case self::TYPE_TECHNICAL:
		return 'Technical';
	    case self::TYPE_JOB :
		return 'Job';
	    case self::TYPE_RESUME :
		return 'Resume';
	    default : return 'Equipment';
	}
    }

    public function getAdNumber() {
	return str_pad($this->ad_id, 9, '0', STR_PAD_LEFT);
    }

    /**
     * get array status support
     * @return array
     */
    public static function getStatusArray() {
	return array(
	    self::STATUS_APPROVE => 'Publish',
	    self::STATUS_DENY => 'Deny',
	    self::STATUS_PENDING => 'Pending'
	);
    }

    public function getStatusText() {
	switch ($this->status) {
	    case self::STATUS_APPROVE : return 'Published';
	    case self::STATUS_DENY : return 'Denied';
	    case self::STATUS_PENDING : return 'Pending';
	    default : return 'Undefined';
	}
    }

    public function afterFind() {
	parent::afterFind();

	if ($this->expire_time) {
	    $this->expireDate = date('Y-m-d', $this->expire_time);
	}
    }

    public function afterDelete() {
	parent::afterDelete();
	db()->createCommand()->delete('{{ads_categories}}', 'ad_id = ' . $this->ad_id);
//delete all
	db()->createCommand()->delete('{{ad_meta}}', 'ad_id = ' . $this->ad_id);
    }

    /*
     * get all type ads
     */

    public static function getAllType() {
	return array(
	    self::TYPE_EQUIPMENT => 'Equipment',
	    self::TYPE_JOB => 'Job',
	    self::TYPE_RESUME => 'Resume',
	    self::TYPE_SUPPLY => 'Supply',
	    self::TYPE_TECHNICAL => 'Technical',
	    self::TYPE_VENDOR => 'Vendor'
	);
    }

    /**
     * get all addition cats 
     * 
     * @return array addition categories
     */
    public function getAllAdditionCat() {
	$aAdditionCats = array();
	if ($this->categories) {
	    foreach ($this->categories as $cat) {
		$aAdditionCats[] = $cat->category_id;
	    }
	}
	return $aAdditionCats;
    }

}

